#include "Logger.h"


#include <iostream>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <stdexcept>
#include <sstream>

const char* Logger::s_level[LEVEL_COUNT]={
        "INFO",
        "WARN",
        "ERROR"
};

Logger *Logger::m_instance = NULL;

Logger::Logger(){

}

Logger::~Logger(){

}

//生产单例对象，防止空指针
Logger * Logger::instance(){
    if(m_instance==NULL){
        m_instance = new Logger();
    }
    return m_instance;
}

void Logger::open(const std::string & filename){
    m_filename=filename;
    m_fout.open(filename,/*ios_base::out | */std::ios_base::app);
    if(m_fout.fail()){
        throw std::logic_error("open file failed"+filename);
    }
}

void Logger::close(){
    m_fout.close();
}

void Logger::log(Level level,std::string file,int line,std::string format){
    if(m_fout.fail()){
        throw std::logic_error("open file failed"+m_filename);
    }
    //记录时间
    time_t nowtime;
    struct tm* p;
    time(&nowtime);
    p=localtime(&nowtime);
    std::string s_t=Logger::Convert(p->tm_year+1900);
    s_t+="-";
    s_t+= Logger::Convert(p->tm_mon+1);
    s_t+="-";
    s_t+= Logger::Convert(p->tm_mday);
    s_t+="-";
    s_t+=Logger::Convert(p->tm_hour);
    s_t+=":";
    s_t+= Logger::Convert(p->tm_min);
    s_t+=":";
    s_t+= Logger::Convert(p->tm_sec);
    s_t+="\n";
    m_fout<<s_t;
    m_fout<<file<<"\nat "<<line<<"\n";
    m_fout<<format;
    m_fout<<"\n";
    m_fout.flush();
}

std::string Logger::Convert(float Num){
    std::ostringstream oss;
    oss<<Num;
    std::string str(oss.str());
    return str;
}

//如何记录如下
//Logger::instance()->open("filename");
//Logger::instance()->log(Logger::DEGUG,__FILE__,__LINE__,"你想传入的内容")
//or用debug（format）代替log函数